<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        @clear="queryEnterprise"
        clearable
        placeholder="请输入内容"
        v-model="queryData.name"
        class="search-main"
      />
      <el-button type="primary" @click="queryEnterprise">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addEnterprise')"
        >添加企业</el-button
      >
    </div>
    <!-- 企业表格 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="expandChange">
        <el-table-column type="expand">
          <!--
           知识点：旧版的vue插槽写法是 slot-scope，而elmUI的文档里面
          还是沿用这种写法，实际一般都使用v-slot（简写为#） 
          -->
          <template #default="scope">
            <!-- 合同表格 -->
            <el-table :data="scope.row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <!-- 
              知识点：自定义展示表格内的内容，有两种方式（本项目里两种方式都有使用到）：
              1.使用官方提供的formatter	属性(不够灵活，推荐使用方法2)
              2.使用插槽的方式，给默认插槽传递内容就是单元格展示的内容（下面就是使用插槽的案例）
              -->
              <el-table-column label="租赁起始时间" prop="startTime">
                <template #default="rent">
                  {{ formatRentTime(rent.row) }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="rent"
                  ><el-tag :type="formatRentStatus(rent.row.status)[1]">{{
                    formatRentStatus(rent.row.status)[0]
                  }}</el-tag></template
                >
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="rent">
                  <el-button
                    :disabled="rent.row.status === 3"
                    size="mini"
                    type="text"
                    @click="releaseRent(rent.row.id, scope.$index)"
                    >退租</el-button
                  >
                  <!-- 
                  知识点：【经验】作用域插槽中，每一个template里面的所有内容都可以共享这个template的
                  scope值。如下面删除按钮，scope.$index使用了最外层的scope值，rent.row.id
                  使用了当前层的scope值
                  -->
                  <el-button
                    :disabled="rent.row.status !== 3"
                    size="mini"
                    type="text"
                    @click="deleteRent(rent.row.id, scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" :index="getTableIndex" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)"
              >添加合同</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="$router.push(`/enterpriseRentDetail/${scope.row.id}`)"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="$router.push(`/addEnterprise?id=${scope.row.id}`)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="deleteEnterprise(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <!-- 分页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.page"
        :page-sizes="[2, 4, 6, 10]"
        :page-size="queryData.pageSize"
        layout="total, prev, pager, next,sizes"
        :total="totalPages"
      >
      </el-pagination>
    </div>
    <!-- 添加 模态框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in selectionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              action="#"
              :limit="1"
              :on-exceed="onExceed"
              ref="upload"
              :http-request="uploadRent"
              :before-upload="handleBeforeLoad"
              :before-remove="handleBeforeRemove"
            >
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item class="modalButton">
            <el-button type="primary" @click="submitAddRentForm"
              >确认</el-button
            >
            <el-button @click="closeDialog">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEnterpriseListAPI,
  deleteEnterpriseAPI,
  addEnterpriseRentAPI,
  getEnterpriseRentByIdAPI,
  deleteEnterpriseRentByIdAPI,
  releaseEnterpriseRentByIdAPI
} from '@/api/enterprise'
import { getBUildingListAPI } from '@/api/building'
import { uploadAPI } from '@/api/common'
export default {
  name: 'Enterprise',
  data () {
    return {
      list: [],
      queryData: {
        name: '',
        page: 1,
        pageSize: 2
      },
      totalPages: 0,
      rentDialogVisible: false,
      // 合同表单
      rentForm: {
        buildingId: '',
        rentTime: [],
        contractUrl: '',
        contractId: '',
        type: 0,
        enterpriseId: ''
      },
      rentRules: {
        rentTime: [
          { required: true, message: '请输入租赁起始日', trigger: 'blur' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件', trigger: 'blur' }
        ],
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ]
      },
      selectionList: []
    }
  },
  methods: {
    //退租
    releaseRent (rentId, index) {
      this.$confirm('确认要退租吗？')
        .then(async () => {
          await releaseEnterpriseRentByIdAPI(rentId)
          this.$message.success('删除合同成功')
          const rent = this.list[index].rentList.find(
            item => item.id === rentId
          )
          rent.status = 3
        })
        .catch(() => {})
    },

    /**
     * 删除合同
     * rentId：合同id
     * index：企业数据行索引
     */
    deleteRent (rentId, index) {
      this.$confirm('删除后数据将会永久消失，确认删除吗？')
        .then(async () => {
          await deleteEnterpriseRentByIdAPI(rentId)
          this.$message.success('删除合同成功')
          // 知识点：折叠表格可以实现局部刷新，手动同步一下页面数据即可
          this.list[index].rentList = this.list[index].rentList.filter(
            item => item.id !== rentId
          )
        })
        .catch(() => {})
    },
    //合同状态修饰
    formatRentStatus (status) {
      const statusMap = {
        0: ['待生效', ''],
        1: ['生效中', 'success'],
        2: ['已到期', 'danger'],
        3: ['已退租', 'info']
      }

      return statusMap[status]
    },
    // 合同时间修饰
    formatRentTime (row) {
      return `${row.startTime} - ${row.endTime}`
    },

    //展开折叠列表
    //知识点：参数一是当前行的数据，参数二是当前展开的所有行数据（数组）
    async expandChange (row, expanded) {
      // console.log(row, expanded)
      const isExpanded = expanded.find(item => {
        return item.id === row.id
      })
      // 表示当前行是折叠状态
      if (!isExpanded) return
      const { data } = await getEnterpriseRentByIdAPI(row.id)
      row.rentList = data
    },
    // 添加合同
    submitAddRentForm () {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        const [startTime, endTime] = this.rentForm.rentTime
        this.rentForm.startTime = startTime
        this.rentForm.endTime = endTime
        delete this.rentForm.rentTime

        await addEnterpriseRentAPI(this.rentForm)
        this.$message.success('添加合同成功')
        this.closeDialog()
        this.getEnterpriseList()
      })
    },

    handleBeforeRemove (file, fileList) {
      // 删除文件，同步修改数据
      this.rentForm.contractId = ''
      this.rentForm.contractUrl = ''
      //单独校验一次
      this.$refs.addForm.validateField('contractId')
    },
    handleBeforeLoad (file) {
      const allowedTypes = [
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/pdf'
      ]
      if (!allowedTypes.includes(file.type)) {
        this.$message.warning('文件格式不正确')
        return false
      }
      if (file.size / 1024 / 1024 > 5) {
        this.$message.warning('文件大小不能超过5M')
        return false
      }
    },
    onExceed () {
      this.$message.info('只能上传一个文件，如需更换请移除后再重新上传')
    },
    async uploadRent (upload) {
      const formData = new FormData()
      formData.append('file', upload.file)
      formData.append('type', 2)
      const { data } = await uploadAPI(formData)
      this.$message.success('上传成功')

      this.rentForm.contractId = data.id
      this.rentForm.contractUrl = data.url
      // this.$refs.addForm.validateField('contractId')
      this.$nextTick(() => {
        this.$refs.addForm.validateField('contractId')
      })
    },
    //添加合同展示
    async addRent (id) {
      // 填充企业id
      this.rentForm.enterpriseId = id
      const res = await getBUildingListAPI()
      this.selectionList = res.data
      this.rentDialogVisible = true
    },

    closeDialog () {
      this.rentDialogVisible = false
      //清空数据
      //知识点：elmui的这个方法只能初始化绑定了prop属性的字段，其他字段不可以处理
      this.$refs.addForm.resetFields()
      this.$refs.upload.clearFiles()
      this.rentForm = {
        buildingId: '',
        rentTime: [],
        contractUrl: '',
        contractId: '',
        type: 0,
        enterpriseId: ''
      }
    },

    //删除企业
    async deleteEnterprise (id) {
      this.$confirm('删除后数据将永久消失，确认要删除？', '提示')
        .then(async () => {
          await deleteEnterpriseAPI(id)
          this.$message.success('删除企业成功')
          if (this.list.length === 1 && this.queryData.page > 1) {
            this.queryData.page--
          }
          this.getEnterpriseList()
        })
        .catch(() => {})
    },
    //查询企业
    queryEnterprise () {
      // 知识点：分页表格查询都需x要重置页码，不然可能导致数据不显示
      this.queryData.page = 1
      this.getEnterpriseList()
    },
    handleCurrentChange (val) {
      this.queryData.page = val
      this.getEnterpriseList()
    },
    handleSizeChange (val) {
      this.queryData.pageSize = val
      this.getEnterpriseList()
    },
    async getEnterpriseList () {
      const { data } = await getEnterpriseListAPI(this.queryData)
      // 知识点：【重要经验】针对可展开的表格，其每一行的子数据都可以作为属性，放到父数据对象里面，
      // 如自定义一个列表rentList来维护
      this.list = data.rows.map(item => {
        return {
          ...item,
          rentList: []
        }
      })

      this.totalPages = data.total
    },
    getTableIndex (index) {
      return index + 1 + (this.queryData.page - 1) * this.queryData.pageSize
    }
  },
  created () {
    this.getEnterpriseList()
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
.modalButton {
  text-align: right;
}
</style>
